package com.ruoyi.student.service;

import com.ruoyi.college.mapper.SecondLevelSubjectMapper;
import com.ruoyi.college.service.ICollegeService;
import com.ruoyi.college.service.IFirstLevelSubjectService;
import com.ruoyi.college.service.ISecondLevelSubjectService;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.major.service.ImajorService;
import com.ruoyi.student.domain.StudentInfo;
import com.ruoyi.student.domain.StudentRegistration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import jakarta.annotation.Resource;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

@Service
public class StudentRegistrationImportService {

    @Autowired
    private IStudentInfoService studentInfoService;
    @Autowired
    private ICollegeService collegeService;
    @Autowired
    private ImajorService majorService;
    @Autowired
    private IStudentRegistrationService studentRegistrationService;
    @Autowired
    private IFirstLevelSubjectService firstLevelSubjectService;
    @Autowired
    private ISecondLevelSubjectService secondLevelSubjectService;


    // 可以根据实际情况注入学院和专业服务，用于查询ID
    // @Resource
    // private ICollegeService collegeService;
    // @Resource
    // private IMajorService majorService;

    // 存储导入进度的线程安全Map
    private final Map<String, ImportProgress> importProgressMap = new ConcurrentHashMap<>();

    /**
     * 异步执行从StudentInfo到StudentRegistration的批量导入
     */
    @Async
    @Transactional(rollbackFor = Exception.class)
    public Future<ImportResult> doImport(String batchNo) {
        // 初始化进度信息
        ImportProgress progress = new ImportProgress();
        progress.setBatchNo(batchNo);
        progress.setStatus("处理中");
        progress.setProgress(0);
        importProgressMap.put(batchNo, progress);

        try {
            // 获取当前系统时间，用于确定当前学年和学期
            Calendar calendar = Calendar.getInstance();
            int currentMonth = calendar.get(Calendar.MONTH) + 1; // 月份从0开始，所以+1
            int currentYear = calendar.get(Calendar.YEAR);

            // 确定当前学年和学期
            String currentAcademicYear;
            if (currentMonth <= 6) {
                // 上半年（1-6月）属于上学年
                //转为字符串如20252026
                currentAcademicYear = (currentYear - 1) + "" + currentYear;
            } else {
                // 下半年（7-12月）属于本学年
                currentAcademicYear = currentYear + "" + (currentYear + 1);
            }
            // 1. 查询所有需要处理的学生信息
            List<StudentInfo> studentInfoList = studentInfoService.selectStudentInfoList(new StudentInfo());
            int total = studentInfoList.size();
            progress.setTotal(total);
            importProgressMap.put(batchNo, progress);

            if (total == 0) {
                progress.setStatus("完成");
                progress.setProgress(100);
                return new AsyncResult<>(new ImportResult(batchNo, 0, "无学生信息需要导入"));
            }

            // 2. 批量查询当前学年已存在的注册信息，避免重复导入
            StudentRegistration query = new StudentRegistration();
            List<StudentRegistration> existingRegistrations = new ArrayList<>();

            // 查询当前学年第一学期的注册记录
            query.setRegistrationSemester(currentAcademicYear + "01");
            existingRegistrations.addAll(studentRegistrationService.selectStudentRegistrationList(query));

            // 查询当前学年第二学期的注册记录
            query.setRegistrationSemester(currentAcademicYear + "02");
            existingRegistrations.addAll(studentRegistrationService.selectStudentRegistrationList(query));
            System.out.println("当前学年-----：" + currentAcademicYear);
            // 构建学生ID和学期的复合键，用于判断重复（只判断当前学年）
            Set<String> existingStudentSemesterKeys = existingRegistrations.stream()
                    .filter(s -> s.getStudentId() != null && s.getRegistrationSemester() != null)
                    .map(s -> s.getStudentId() + "_" + s.getRegistrationSemester())
                    .collect(Collectors.toSet());

            // 3. 构建批量插入列表
            List<StudentRegistration> insertList = new ArrayList<>(100);
            int successCount = 0;

            for (int i = 0; i < studentInfoList.size(); i++) {
                StudentInfo studentInfo = studentInfoList.get(i);
                String studentId = studentInfo.getStudentId();

                // 校验必要字段
                if (studentId == null || studentInfo.getStudentName() == null) {
                    throw new RuntimeException("学号或姓名为空，无法导入，索引：" + i);
                }

                // 确定该学生的注册学期
                String registrationSemester;
                if (currentMonth <= 6) {
                    // 上半年（1-6月）为上学年的第二学期
                    registrationSemester = currentAcademicYear + "02";
                } else {
                    // 下半年（7-12月）为本学年的第一学期
                    registrationSemester = currentAcademicYear + "01";
                }

                // 构建复合键，判断当前学年该学期是否已存在注册记录
                String studentSemesterKey = studentId + "_" + registrationSemester;
                if (existingStudentSemesterKeys.contains(studentSemesterKey)) {
                    updateProgress(progress, i + 1, total, successCount);
                    continue;
                }

                // 构建注册信息对象
                StudentRegistration registration = new StudentRegistration();
                registration.setId(IdUtils.fastSimpleUUID());
                registration.setStudentId(studentId);
                registration.setStudentName(studentInfo.getStudentName());

                // 映射学院信息
                registration.setCollegeId(studentInfo.getStudentYx()); // 院系作为学院名称
                System.out.println("导入学生注册-----：" + registration+studentInfo.getStudentYx());
                // 如果有学院服务，可以通过学院名称查询ID
                // if (StringUtils.isNotBlank(registration.getCollegeName())) {
                //     College college = collegeService.getCollegeByName(registration.getCollegeName());
                //     if (college != null) {
                //         registration.setCollegeId(college.getId());
                //     }
                // }
                registration.setCollegeName(collegeService.selectCollegeByCollegeCode(registration.getCollegeId()).getCollegeName());
                // 映射专业信息
                registration.setMajorId(studentInfo.getStudentZy()); // 专业名称
                //专业名字如果不为空则查询
                if (StringUtils.isNotBlank(registration.getMajorId())) {
                    registration.setMajorName(secondLevelSubjectService.selectSecondLevelSubjectNameByFSAndSS(studentInfo.getStudentYx(), studentInfo.getStudentZy()));
                }
                // 同理，如果有专业服务，可以通过专业名称查询ID
                // if (StringUtils.isNotBlank(registration.getMajorName())) {
                //     Major major = majorService.getMajorByName(registration.getMajorName());
                //     if (major != null) {
                //         registration.setMajorId(major.getId());
                //     }
                // }

                // 设置注册学期（根据系统时间自动判断）

                registration.setRegistrationSemester(registrationSemester);

                // 注册时间留空，待学生实际注册时再设置
                registration.setRegistrationTime(null);

                // 注册状态默认为0（待审核）
                registration.setRegistrationStatus(0);

                // 其他可选字段
                registration.setRemark("系统自动导入自学生基本信息");

                insertList.add(registration);
                successCount++;

                // 每100条批量插入一次
                if (insertList.size() >= 100) {
                    studentRegistrationService.batchInsert(insertList);
                    insertList.clear();
                }

                // 更新进度
                updateProgress(progress, i + 1, total, successCount);
            }

            // 插入剩余数据
            if (!insertList.isEmpty()) {
                studentRegistrationService.batchInsert(insertList);
            }

            // 完成处理
            progress.setStatus("完成");
            progress.setProgress(100);
            progress.setSuccessCount(successCount);
            importProgressMap.put(batchNo, progress);

            return new AsyncResult<>(new ImportResult(batchNo, successCount, "导入成功"));

        } catch (Exception e) {
            progress.setStatus("失败");
            System.out.println("导入失败：" + e.getMessage());
            progress.setErrorMsg(e.getMessage());
            importProgressMap.put(batchNo, progress);
            return new AsyncResult<>(new ImportResult(batchNo, 0, "导入失败：" + e.getMessage()));
        }
    }

    /**
     * 查询导入进度
     */
    public ImportProgress getImportProgress(String batchNo) {
        return importProgressMap.getOrDefault(batchNo, new ImportProgress());
    }

    /**
     * 更新进度信息
     */
    private void updateProgress(ImportProgress progress, int current, int total, int successCount) {
        progress.setProgress((int) ((current * 1.0 / total) * 100));
        progress.setSuccessCount(successCount);
        importProgressMap.put(progress.getBatchNo(), progress);
    }

    // 导入进度内部类
    public static class ImportProgress {
        private String batchNo;
        private String status; // 处理中/完成/失败
        private int progress; // 0-100
        private int total; // 总条数
        private int successCount; // 成功条数
        private String errorMsg; // 错误信息

        // Getter和Setter
        public String getBatchNo() { return batchNo; }
        public void setBatchNo(String batchNo) { this.batchNo = batchNo; }
        public String getStatus() { return status; }
        public void setStatus(String status) { this.status = status; }
        public int getProgress() { return progress; }
        public void setProgress(int progress) { this.progress = progress; }
        public int getTotal() { return total; }
        public void setTotal(int total) { this.total = total; }
        public int getSuccessCount() { return successCount; }
        public void setSuccessCount(int successCount) { this.successCount = successCount; }
        public String getErrorMsg() { return errorMsg; }
        public void setErrorMsg(String errorMsg) { this.errorMsg = errorMsg; }
    }

    // 导入结果内部类
    public static class ImportResult {
        private String batchNo;
        private int successCount;
        private String msg;

        public ImportResult(String batchNo, int successCount, String msg) {
            this.batchNo = batchNo;
            this.successCount = successCount;
            this.msg = msg;
        }

        // Getter和Setter
        public String getBatchNo() { return batchNo; }
        public void setBatchNo(String batchNo) { this.batchNo = batchNo; }
        public int getSuccessCount() { return successCount; }
        public void setSuccessCount(int successCount) { this.successCount = successCount; }
        public String getMsg() { return msg; }
        public void setMsg(String msg) { this.msg = msg; }
    }
}
